/**
 * 模态框
 */
module.exports = function($scope, $state, $resource, $modalInstance, item, roleList){

    init();
	//初始化模板列表
	function init(){
        roleList.save({}, function (res) {
			if (res.errcode === 0) {
				$scope.role_list = res.data;
                loadRoleTemplete();
			} else {
				alert(res.errmsg);
			}
		});
    }

    //加载角色已绑定模板
	function loadRoleTemplete(){
        $resource('/api/as/sc/role/getRoleForTempList', {}, {}).save({'templete_code': item.templete_code}, function (res) {
            if (res.errcode === 0) {
                angular.forEach($scope.role_list, function(item){
                    item.sel = false;
                    for(var i = 0; i < res.data.length; i++){
                        if(item.id == res.data[i].role_id){
                            item.sel = true;
                        }
                    }
                });
            } else {
                alert(res.errmsg);
            }
        });
    }

    //选中角色
	$scope.select = function (info) {
        var para = {
            'templete_code': item.templete_code,
            'role_id': info.id,
            'type': '1'
        };
        updateTemplete(para,info);
	};

    //取消选中角色
	$scope.unselect = function (info) {
        var para = {
            'templete_code': item.templete_code,
            'role_id': info.id,
            'type': '2'
        };
        updateTemplete(para,info);
    };
    
    var updateTemplete = function (para,info){
        $resource('/api/ac/sc/roleService/setTemplete2Role', {}, {}).save(para, function (res) {
            if (res.errcode === 0) {
                info.sel = !info.sel;
            } else {
                alert(res.errmsg);
            }
        });
    }

    //关闭
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };

};